import 'dart:convert';
import 'dart:typed_data';
import 'dart:io';

class GZIPUtils {
  // 将十六进制字符串转换为字节数组
  static Uint8List hexStringToByteArray(String s) {
    int len = s.length;
    Uint8List data = Uint8List(len ~/ 2);
    for (int i = 0; i < len; i += 2) {
      data[i ~/ 2] = int.parse(s.substring(i, i + 2), radix: 16);
    }
    return data;
  }

  // 将 ISO-8859-1 编码的字符串转换为字节数组
  static List<int> ISO_8859_1StringToByteArray(String s) {
    return utf8.encode(s); // Dart 使用 utf8 来处理字符编码
  }

  // 解压缩方法
  static String decompress(String s)   {
    List<int> compressed;

    if (s.startsWith("crypto-hex:")) {
      s = s.substring(11); // 去掉前缀 "crypto-hex:"
      compressed = hexStringToByteArray(s);
    } else if (s.startsWith("crypto-s:")) {
      s = s.substring(9); // 去掉前缀 "crypto-s:"
      compressed = ISO_8859_1StringToByteArray(s);
    } else {
      return ""; // 如果没有匹配的前缀，返回空字符串
    }

    try {
      // 使用 GZIP 解压
      List<int> decompressed =   _decompressGZIP(compressed);
      return utf8.decode(decompressed);
    } catch (e) {
      print('Error during decompression: $e');
      return "";
    }
  }

  // 使用 GZIP 解压缩
  static List<int> _decompressGZIP(List<int> compressed)   {
    try {
      final decoded = GZipCodec().decode(compressed);
      return decoded;
    } catch (e) {
      print('Decompression failed: $e');
      rethrow;
    }
  }
}
